# coding=utf-8
import cv2
import os
from ToMinst import format
from predict import giveresult
from judge import getresult
import string


def del_files(path):
    delList = os.listdir(path)

    for f in delList:
        filePath = os.path.join(path, f)
        os.remove(filePath)


def dootherjpbs(cnt):
    format()

    equation = []

    for i in range(cnt):
        ch = giveresult(str(i) + '.jpg')
        equation.append(ch)
    res = ""
    for e in equation:
        if e == 10:
            res += '+'
        elif e == 11:
            res += '-'
        elif e == 12:
            res += '*'
        elif e == 13:
            res += '/'
        elif e == 14:
            res += '('
        elif e == 15:
            res += ')'
        else:
            res += str(e)

    for index in range(len(res) - 1):
        if res[index] == res[index + 1] and res[index] == '-':
            break
    res1 = res[:index]
    res2 = res[index + 2:]

    print("算式是", res1 + '=')
    getresult(res1)

    print("您的结果是:", res2)

    if abs(float(getresult(res1)) - float(res2)) < 0.00001:
        rst = "正确"
    else:
        rst = "错误"
    put = "识别的算式" + res1 + "\n您的结果：" + res2 + "\n判断结果：" + rst + "\n"

    # 删除。。。
    del_files("input")
    del_files("output")

    return put


def getCharacter(filename, threshold=100):
    NUM = []
    RECT = []
    YUZHI = int(threshold)
    srcImage = cv2.imread(filename)  # 根据路径读取一张图片
    # print(len(srcImage[0]))

    grayImage = cv2.cvtColor(srcImage, cv2.COLOR_BGR2GRAY)
    #print(type(YUZHI))
    ret, Image = cv2.threshold(grayImage, YUZHI, 255, cv2.THRESH_BINARY_INV)

    Image, contours, heirs = cv2.findContours(Image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)

    # 去除小噪点
    for c in contours:
        tmp = cv2.boundingRect(c)
        if tmp[2] < 10 and tmp[3] < 10:
            continue
        RECT.append(tmp)
    # 去除噪声并排序
    RECT.sort(key=lambda x: (x[1], x[0]))
    val = []
    height = -200
    cnt = 0
    for r in RECT:
        if abs(r[1] - height) <= 20:
            cnt = cnt + 1
        else:
            if cnt >= 3:
                val.append(height)
            cnt, height = 1, r[1]
    # 完成
    if cnt >= 3:
        val.append(height)
    # val保存的是每个算式的合法高度
    RECT.sort(key=lambda x: x[0])
    ans = []
    cnt = len(val)
    print(cnt)
    for i in range(cnt):
        ans.append([])

    rst = ""

    for r in RECT:
        x, y, w, h = r[0], r[1], r[2], r[3]
        flag = 1
        for i, v in enumerate(val):
            if abs(v - y) <= 20:
                ans[i].append(r)
                flag = 0
                break;

    print(ans)

    for j in range(cnt):
        # print(x, y, w, h)
        for i, r in enumerate(ans[j]):
            x, y, w, h = r[0], r[1], r[2], r[3]
            NUM.append(srcImage[y:y + h, x:x + w])
            NUM[i] = cv2.cvtColor(NUM[i], cv2.COLOR_BGR2GRAY)
            ret, NUM[i] = cv2.threshold(NUM[i], YUZHI, 255, cv2.THRESH_BINARY_INV)

            # cv2.imshow(str(i), NUM[i])
            # NUM[i] = cv2.resize(NUM[i], (28, 28))
            cv2.imwrite("input/" + str(i) + ".jpg", NUM[i])

        rst = rst + dootherjpbs(len(ans[j])) + "\n"
        NUM = []
    return rst